'use strict';

const Controller = require('egg').Controller;

class TodoController extends Controller {
  constructor(ctx) {
    super(ctx);

    this.createRule = {
      id: 'string',
      title: 'string',
      completed: { type: 'boolean', required: false },
    };
  }

  async index() {
    const { ctx, service } = this;
    const query = ctx.request.query;
    const filter = query.filter || 'all';
    const list = await service.todo.index(filter);
    ctx.body = {
      code: 1,
      msg: 'query success!',
      list,
    };
  }

  async create() {
    const { ctx, service } = this;
    const body = ctx.request.body;
    ctx.validate(this.createRule, body);

    const result = await service.todo.create({
      id: body.id,
      title: body.title,
      completed: false,
    });

    ctx.body = {
      code: 1,
      id: result.id,
      msg: 'request sucess!',
    };
    ctx.state = 200;
  }

  async update() {
    const { ctx, service } = this;
    const id = ctx.params.id || '';
    const result = await service.todo.update(id);

    ctx.body = {
      code: result ? '1' : '0',
      msg: result ? 'control sucess!' : 'please refresh your page.',
    };
  }

  // clear completed
  async destroy() {
    const { ctx, service } = this;
    const result = await service.todo.destroy();
    ctx.body = {
      code: result ? 1 : 0,
      msg: result ? 'delete success!' : 'delete error',
      list: this.service.todo.index(),
    };
  }
}

module.exports = TodoController;
